#!/bin/sh
#
# Check for ruby style errors


if git rev-parse --verify HEAD >/dev/null 2>&1
then
	against=HEAD
else
	# Initial commit: diff against an empty tree object
	# Change it to match your initial commit sha
	against=123acdac4c698f24f2352cf34c3b12e246b48af1
fi

# Check if rubocop is installed for the current project
bin/bundle exec rubocop -v >/dev/null 2>&1 || { echo >&2 "[Ruby Style][Fatal]: Add rubocop to your Gemfile"; exit 1; }

# Get only the staged files
FILES="$(git diff --cached --name-only --diff-filter=AMC | grep "\.rb$" | tr '\n' ' ')"

echo "[Ruby Style][Info]: Checking Ruby Style"

if [ -n "$FILES" ]
then
	echo "[Ruby Style][Info]: ${FILES}"
	
	if [ ! -f '.rubocop.yml' ]; then
	  echo "[Ruby Style][Warning]: No .rubocop.yml config file."
	fi
	
	# Run rubocop on the staged files
	bin/bundle exec rubocop ${FILES}
	
	if [ $? -ne 0 ]; then
	  echo "[Ruby Style][Error]: Fix the issues and commit again"
      echo "[Ruby Style][Error]: 修复这些缺陷之后再尝试提交"
	  exit 1
	fi
else
	echo "[Ruby Style][Info]: No files to check"
fi

exit 0